//
//  VKJiFenShopController.m
//  V-Learn
//
//  Created by liubo on 2019/1/8.
//  Copyright © 2019 yxk. All rights reserved.
//

#import "VKJiFenShopController.h"
#import "VKJiFenShopCell.h"
#import "VKJiFenShopModel.h"
#import "VKJiFenShopHeaderView.h"
#import "VKJiFenShopDetailController.h"
#import "VKMeJiFenController.h"
#import "VKJiFenShopDHController.h"


@interface VKJiFenShopController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *jiFenShopCollectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageNums;
@property (nonatomic, strong) VKJiFenShopHeaderView *headerView;
@end

@implementation VKJiFenShopController
-(UICollectionView *)jiFenShopCollectionView{
    if (_jiFenShopCollectionView == nil) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = CGSizeMake(([UIScreen cz_screenWidth] - 40) / 2.0, ([UIScreen cz_screenWidth] - 40) / 2.0 + 52);
        flowLayout.minimumInteritemSpacing = 10;
        flowLayout.minimumLineSpacing = 10;
        _jiFenShopCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen cz_screenWidth], [UIScreen cz_screenHeight] - LBNAVBAR_HEIGHT) collectionViewLayout:flowLayout];
        _jiFenShopCollectionView.delegate = self;
        _jiFenShopCollectionView.dataSource = self;
        [_jiFenShopCollectionView registerClass:[VKJiFenShopCell class] forCellWithReuseIdentifier:@"VKJiFenShopCell"];
        _jiFenShopCollectionView.backgroundColor = [UIColor cz_colorWithHex:0xFFF5F6F8];
        
        [_jiFenShopCollectionView registerClass:[VKJiFenShopHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"VKJiFenShopHeaderView"];
        _jiFenShopCollectionView.backgroundColor = [UIColor whiteColor];
    }
    return _jiFenShopCollectionView;
}
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"积分商城";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.jiFenShopCollectionView];

    self.edgesForExtendedLayout = @[];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupRightItem];
    [self setupLeftRefresh];

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSMutableDictionary *pagramsD = @{@"token":[UserModel getUserModel].token}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeQueryQueryIntegralRecord withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
//        NSLog(@"result:%@",result);
        if ([result[@"code"] integerValue] == 200) {
            self.headerView.jifenLabel.text = [NSString stringWithFormat:@"我的积分: %@",result[@"data"][@"allIntegralNum"]];
//            self.jifenString = [NSString stringWithFormat:@"%@",result[@"data"][@"allIntegralNum"]];
//            jifenLabel.text = [NSString stringWithFormat:@"我的积分: %@",result[@"data"][@"allIntegralNum"]];
        }else{
//            jifenLabel.text = [NSString stringWithFormat:@"我的积分: 0"];
        }
        [self.jiFenShopCollectionView reloadData];
        
    }];
}
//刷新
- (void)setupLeftRefresh
{   //下拉
    self.jiFenShopCollectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(setupLoadData)];
    //上拉
    self.jiFenShopCollectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(setupLoadMoreData)];

    [self.jiFenShopCollectionView.mj_header beginRefreshing];
}
- (void)setupLoadData{
    _page = 1;
    _pageNums = 10;
    [self setupLoadFirstData];
}
/**
 加载更多数据
 */
- (void)setupLoadMoreData{

    ++(_page);
    _pageNums = 10;
    [self setupLoadFirstData];
}//决定footer的状态
- (void)checkFooterState{

    [self.jiFenShopCollectionView.mj_footer endRefreshingWithNoMoreData];
}

- (void)setupLoadFirstData{
    VKWeakSelf(self)
//    @"token":[UserModel getUserModel].token,
    NSMutableDictionary *pagramsD = @{@"page":[NSString stringWithFormat:@"%ld",(long)_page],@"num":[NSString stringWithFormat:@"%ld",(long)_pageNums]}.mutableCopy;
    [WYHXNetWorkService netWorkSerViceRequestWithGetUrl:WKMeQueryIntegralGoods withPostParams:pagramsD withBlock:^(NSDictionary *result, NSError *error) {
        // goodsType 0是实体  1是代金券
        if ([result[@"code"]integerValue] == 200) {
            if (weakself.page == 1) {
                [self.dataArray removeAllObjects];
            }

            for (NSDictionary *dic in result[@"data"]) {
                VKJiFenShopModel *model = [VKJiFenShopModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:model];
                
            }
            if ([result[@"data"] count] < 10) {
                //不能加载更多数据
                [self checkFooterState];
                [MBProgressHUD showSuccess:@"已加载全部数据" toView:self.view];
            }else{
                [self.jiFenShopCollectionView.mj_footer endRefreshing];
            }
        }else{
            [MBProgressHUD showSuccess:result[@"msg"] toView:self.view];
        }
        [weakself.jiFenShopCollectionView reloadData];

        [self.jiFenShopCollectionView.mj_header endRefreshing];
    }];

}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    VKJiFenShopCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"VKJiFenShopCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor whiteColor];
    cell.model = self.dataArray[indexPath.row];

    return cell;
}

/**
 立即兑换
 */
- (void)duiHuanButtonClick:(UIButton *)btn{
//    VKJiFenShopModel *model = self.dataArray[btn.tag];
//    WYHXDingDanController *dingDan = [[WYHXDingDanController alloc]initWithGid:model.gId];
//    [self.navigationController pushViewController:dingDan animated:YES];
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(5, 15, 5, 15);
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    [self.navigationController pushViewController:[[VKJiFenShopDetailController alloc]initWithModel:self.dataArray[indexPath.row]] animated:YES];
}

// 右边Item
- (void)setupRightItem{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 70, 30);
    [button setTitle:@"兑换记录" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button setTitleColor:[UIColor cz_colorWithRed:40 green:40 blue:40] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:button] ;
//    [button mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.height.equalTo(@30);
//        make.width.equalTo(@70);
//    }];
    [button addTarget:self action:@selector(buttonItemClick) forControlEvents:UIControlEventTouchUpInside];
}
- (void)buttonItemClick{
    
    VKJiFenShopDHController *dh = [[VKJiFenShopDHController alloc]init];
    [self.navigationController pushViewController:dh animated:YES];
    
}
// 组头视图、尾视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionReusableView *reusableview = nil;
    
    if (kind == UICollectionElementKindSectionHeader){
        if (indexPath.section == 0) {
            VKJiFenShopHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"VKJiFenShopHeaderView" forIndexPath:indexPath];
            self.headerView = headerView;
            reusableview = headerView;
//            headerView.vkJiFenShopBlock = ^{
//                VKMeJiFenController *me = [[VKMeJiFenController alloc]init];
//                me.
//                [self presentViewController:me animated:YES completion:nil];
//            };
            headerView.vkJiFenShopBlock = ^(NSString *jifen) {
                VKMeJiFenController *me = [[VKMeJiFenController alloc]init];
                me.jifen = jifen;
                [self presentViewController:me animated:YES completion:nil];
            };
        }
    }
    return reusableview;
}

/// head宽高
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    
    if (section == 0) {
        return CGSizeMake([UIScreen cz_screenWidth], 72);
    }
    // mark -- headerView = nil  如果这个地方不是CGSizeZero ,就会出现崩溃
    return CGSizeZero;
    
}
@end
